import reg from "@/utils/reg";

const filters = {
    formatPer(v) {
        if (v)
            return v.toFixed(2) + "%";
        return 0.0
    },
    formatMoney(v) {
        // 1,234,567.89
        if (v)
            return v.toFixed(2).replace(reg.formatMoney, ",")
        return 0
    },
    phoneCloak(v) {
        return v.substring(0, 3) + "******" + v.substring(9)
    },
    formatDate(v, pattern) {
        if (typeof (v) == "string") {
            v = new Date(v);
        }

        if (pattern === undefined) {
            pattern = 'yyyy-MM-dd HH:mm:ss';
        }

        function zero(v) {
            return v < 10 ? "0" + v : v;
        }

        /*
        let year = zero(v.getFullYear());
        let month = zero(v.getMonth() + 1);
        let day = zero(v.getDate());
        let hour = zero(v.getHours());
        let minutes = zero(v.getMinutes());
        let seconds = zero(v.getSeconds());

        pattern = pattern.replace(/yyyy/, year)
        pattern = pattern.replace(/MM/, month);
        pattern = pattern.replace(/dd/, day);
        pattern = pattern.replace(/HH/, hour);
        pattern = pattern.replace(/mm/, minutes);
        pattern = pattern.replace(/ss/, seconds);

        return pattern;
        */

        let d = v;
        return pattern.replace(/y+|M+|d+|H+|h+|m+|s+|S+/g, function (v) {
            switch (v) {
                case "yy": // 2位年
                    return (d.getFullYear() + "").substring(2);
                case "yyyy": // 4位年
                    return d.getFullYear();
                case "MM": // 月：不足10前面补零
                    return zero(d.getMonth() + 1)
                case "M": // 月
                    return d.getMonth();
                case "dd": // 月：不足10前面补零
                    return zero(d.getDate());
                case "d":
                    return d.getDate();
                case "HH": // 时(24小时制)：不足10前面补零
                    return zero(d.getHours());
                case "H": // 时(24小时制)
                    return d.getHours();
                case "hh": // 时(12小时制)：不足10前面补零
                    return zero(d.getHours() / 12);
                case "h": // 时(12小时制)
                    return d.getHours() / 12;
                case "mm": // 分：不足10前面补零
                    return zero(d.getMinutes());
                case "m":
                    return d.getMinutes();
                case "ss": // 秒：不足10前面补零
                    return zero(d.getSeconds());
                case "s":
                    return d.getSeconds();
                case "SSS":
                    return d.getMilliseconds();
                default:
                    return "?"
            }
        });
    }
}

export default filters